<?php 	
/**
 * 密友圈内容管理
 */  
// include('emoji.php');
class micontent {

	public function getMiContentList($qId,$order,$start,$limit){
	    $uId=Session::$user['userId'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $vendorModel=M("micontent");
	    Session::switchCustomer($customerId);
	    $pageStart=$start*$limit;
	    $where["qv.quanId"]=array('eq',$qId);
	    $where["wmc.deleted"]=array('eq',0);

	    $timegroup= $vendorModel->query(
	    	"SELECT DATE_FORMAT(b.publishTime,'%Y/%m/%d') AS miniday,GROUP_CONCAT(b.id) AS ids"
	    	." FROM wx_miyouquan a INNER JOIN wx_micontent b ON a.vid=b.vId WHERE a.id=$qId and b.deleted=0"
	    	." GROUP BY miniday ORDER BY miniday DESC LIMIT $pageStart,$limit "
	    );
	    //按天分组循环
	    foreach($timegroup as $key=>$val){
	    	$ids=$val["ids"];
	        $result= $vendorModel->query(
	        	"SELECT * FROM (SELECT b.id,b.picUrl,b.title,b.createTime,b.publishTime,b.recomment,share.id as sId,com.deleted as comment FROM wx_miyouquan a"
				." INNER JOIN wx_micontent b ON a.vid=b.vId AND a.id=$qId AND b.deleted=0"
				." INNER JOIN wx_mishare share ON share.moduleId=b.id AND share.module='micontent'"
				." LEFT JOIN (SELECT sId as msId,deleted  FROM wx_mirecomment WHERE uId=$uId AND quanId=$qId and deleted=0) com ON com.msId=share.id
				) c WHERE c.id IN ($ids) ORDER BY c.publishTime DESC"
	        );
	        $timegroup[$key]["list"]=$result;
	    }	  
	    $total =$vendorModel->query(
	    	"select count(1) as t from (SELECT DATE_FORMAT(b.publishTime,'%Y-%m-%d') AS miniday"
	    	." FROM wx_miyouquan a INNER JOIN wx_micontent b ON a.vid=b.vId WHERE a.id=$qId and b.deleted=0 GROUP BY miniday) as c"
	    );
	    $out=new StdClass();
	    if($total && count($total) >0 ){
	    	$out->count=$total[0]["t"];
	    }
	    $out->pageCount=getPageCount($count,$limit);  
	    $out->list=$timegroup;
	    Output::instance()->object($out);
	}
	public function getMiContent($param){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$uid = Session::$user['userId'];
		$result["guid"]=$guid;
		$result["qId"]=$param->qId;
		$result["fromUId"]=$uid;
	    Output::instance()->module('micontent',"content_list")->object($result);
	}
	public function getMiContentByAccessTag($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $uid = Session::$user['userId'];
	    $customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $CotentModel = M("micontent");
	    $CotentTagModel = M("micontent_tag");	
	    $CotentTagListModel = M("micontent_tag_list");	    
	    Session::switchCustomer($customerId);
	    $where['id']=$param->id;
	    $contentarr=$CotentModel->where($where)->find();	
	    $tagwhere['tagId']=array('in',$contentarr['tags']);
	    $tagwhere['s.deleted']=0;
	    $tagwhere['webPageId']=array('neq',$param->id);
	    $arr=$CotentTagListModel
	    ->distinct(true)->alias("mtl")
	    ->field('s.title,s.recomment,s.picUrl,s.createTime,s.publishTime,s.id')
	    ->join("inner join wx_micontent s on s.id=mtl.webPageId")
	    ->where($tagwhere)->order('s.id desc')
	    ->limit(0,5)
	    ->select();
	    $res["list"]=$arr;
	    Output::instance()->object($res);
	
	}

	/**
	 * 获取内容详情
	 * @param $param
	 */
	public function getMiContentDetail($param){
	    $retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $uid = Session::$user['userId'];
	    $id=$param->id;
		$miUId=$param->miUId;
		$qId = $param->qId;
		$fromUserName = $param->fromUserName;
		$startUid = $param->miUId;
		if(!$miUId||!$qId){
			$quanInfo = self::isPartner();
			$qId = $quanInfo['qId'];
			$miUId = $quanInfo['uId'];
		}
		$userName = Session::$user['userName'];
		$customerId = Session::$user['customerId'];
		$allUserModel = D("user");
	    Session::switchCustomer(0);
	    $CotentModel = M("micontent");	   
	    $formInfo_tab = M("form");
	    $formField_tab = M("form_field");
	    $MplModel = M("micontent_product_list");
		$shareModel = M("mishare");
	    $specModel = M("module_product_specification");
		$tagList = M("micontent_tag_list");
		$quan_tab = M('miyouquan');
		$quan_user_tab = M('quan_user');
$mimall_user_tab=M('mimall_user');
		$pointScheme_tab = M('module_point_scheme');
        $posterModel = M('poster');
	    $where["mc.id"]=array('eq',$id);
	    $where["mc.deleted"]=array('eq',0);
	    $where["s.module"]=array('eq','micontent');

		if($uid){
			$micon = $CotentModel->alias('mc')
				->join("left join wx_pb_template tp on mc.tplid=tp.id")
				->join("wx_".$customerId."_user AS au ON au.id=$uid")
				->join("inner join wx_mishare s on s.moduleId=mc.id")
				->join("left join wx_mishare_material m on s.id=m.sId")
				->field("mc.*,au.*,wx.headimgurl,wx.nickname,s.id as sId, tp.tplname, tp.module, m.shareImg, m.title as shareTitle")
				->join("wx_".$customerId."_user_weixin_info AS wx ON wx.userId=au.id")
				->where($where)
				->find();
		}else{
			
			$micon = $CotentModel->alias('mc')
				->join("left join wx_pb_template tp on mc.tplid=tp.id")
				->join("inner join wx_mishare s on s.moduleId=mc.id")
				->join("left join wx_mishare_material m on s.id=m.sId")
				->field("mc.*,s.id as sId,tp.tplname, tp.module, m.shareImg, m.title as shareTitle")
				->where($where)
				->find();
		}
		$micon['moduleId'] = $micon['id'];
		/*判断模板*/
		$templateType = 0;
		if($micon['module'] == 'mi_content'){
			$mediaInfo = WeixinApi::getCustomer($customerId);
			$micon['mediaName'] = $mediaInfo['nick_name'];
			if($micon['tplname'] == '经典'){
				$templateType = 1;
			}else if($micon['tplname'] == '微信图文模板'){
				$templateType = 2;
			}else{
				$templateType = 3;
			}
		}
		$micon['templateType'] = $templateType?$templateType:3;
		/*增加关联圈子,表单,密友信息*/
		$micon['relationQid'] = $micon['qid'];
		unset($micon['qid']);
		//判断当前用户quan_user情况
		$micon['isShowQuqnIco'] = 3;
		if($uid){
			$quanConfig = $quan_tab->where(['id'=>$qId])->getField('config');
			if($quanConfig){
				$micon['themeColor'] = json_decode($quanConfig,true)['reveal']['themeColor'];
			}
			$quanUserInfo = M('quan_user')->alias('u')
				->join('inner join wx_miyouquan q on u.qid=q.id')
				->where(['q.cId'=>$customerId, 'u.uid'=>$uid, 'u.deleted'=>0, 'u.status'=>1])
				->field('u.qid,q.name,q.logo,q.config')
				->find();
			if($quanUserInfo !== null){
				if($uid == $startUid || empty($startUid)){
					$micon['isShowQuqnIco'] = 1;	//可进入圈
					//获取来源圈子信息
					$micon['quanLogo'] = $quanUserInfo['logo']?$quanUserInfo['logo']:'';
					$micon['quanName'] = $quanUserInfo['name']?$quanUserInfo['name']:'';
					if($quanUserInfo['config']){
						$micon['themeColor'] = json_decode($quanUserInfo['config'],true)['reveal']['themeColor'];
					}
				}else{
					$micon['isShowQuqnIco'] = 2;
				}
			}else if($micon['relationQid']){
				$micon['isShowQuqnIco'] = 0;	//可加入圈
			}
		}
		Log::write('jie---1221-flag:'.$startUid.'-isShow:'.$micon['isShowQuqnIco'].'-uid:'.$uid);
		if($micon['formId']){
			$formInfo = $formInfo_tab->where(['id'=>$micon['formId'],'cid'=>$customerId,'status'=>0])
				->field('id,formName,type,vendorId,payPrice')
				->find();
			$userInfo = $allUserModel->where(['id' => $uid])->find();
			$formFields = $formField_tab->where(['formId'=>$micon['formId'],'cid'=>$customerId])
				->field('name,describe,placeholder,default,options,requird,key,type,index')->select();
			$fieldArr = [];
			$formFields = list_sort_by($formFields, 'index');
			foreach($formFields as $k=>$v){
				$fieldArr[$k]['name'] = trim($v['name']);
				$fieldArr[$k]['describe'] = trim($v['describe']);
				$fieldArr[$k]['placeholder'] = trim($v['placeholder']);
				$fieldArr[$k]['default'] = $v['default'];
				$fieldArr[$k]['requird'] = $v['requird'];
				$fieldArr[$k]['key'] = $v['key'];
				$fieldArr[$k]['type'] = $v['type'];
				$fieldArr[$k]['index'] = $v['index'];
				$fieldArr[$k]['options'] = trim($v['options']);
				switch($v['key']){
					case 'name':
						empty($userInfo['fullName']) ? '' : $fieldArr[$k]['default'] = $userInfo['fullName'];
						break;
					case 'phone':
						empty($userInfo['phone']) ? '' : $fieldArr[$k]['default'] = $userInfo['phone'];
						break;
					case 'email':
						empty($userInfo['email']) ? '' : $fieldArr[$k]['default'] = $userInfo['email'];
						break;
					case 'city':
						empty($userInfo['city']) ? '' : $fieldArr[$k]['default'] = $userInfo['province'].' '.$userInfo['city'].' '.$userInfo['county'];
						break;
					case 'address':
						empty($userInfo['address']) ? '' : $fieldArr[$k]['default'] = $userInfo['province'].' '.$userInfo['city'].' '.$userInfo['county'].','.$userInfo['address'];
						break;
					case 'verifyPhone':
						empty($userInfo['phone']) ? '' : $fieldArr[$k]['default'] = $userInfo['phone'];
						break;
				}
			}
			$micon['isVerifyPhone'] = $userInfo['isVerifyPhone'];
			$micon['formName'] = $formInfo['formName'];
			$micon['formType'] = $formInfo['type'];
			$micon['formVendorId'] = $formInfo['vendorId'];
			$micon['formPayPrice'] = $formInfo['payPrice'];
			$micon['formInfo'] = $fieldArr;

			$userInfo = $allUserModel->where(['id'=>$uid])->field('fullName,phone,email,city,province,birthday,
			wxNumber,address')->find();
			$miInfo["userInfo"]=$userInfo;
			$micon['payInfo'] = [];
			if($formInfo['type'] == 1){
				$payAndLogistics = R('Mall/getPayAndLogisticsList',
					array(0, 0, null, null, $customerId,null));
				unset($payAndLogistics['shipping']);
				unset($payAndLogistics['deliveryHasDefault']);
				unset($payAndLogistics['payTypeHasDefault']);
				$micon['payInfo'] = $payAndLogistics;
			}
		}

		//默认返回content中内容,新上传的oss内容,则替换成oss中的内容
		if($micon['ossLink']){
			$ossContent = file_get_contents($micon['ossLink']);
			//$micon['content'] = htmlspecialchars_decode($ossContent);
			$micon['content'] = $ossContent;
		}

		Session::switchCustomer($customerId);
		if(!empty($micon['accessTag']) && !empty($userName)){
			setAccessTags($micon['accessTag'],$userName,"micontent", $id);
		}
		Session::switchCustomer(0);
		/*以下部分代码涉及到关联商品,新平台暂用不到*/
	    $mplwhere["mcId"]=$id;
	    $mplwhere["pro.isRemoved"]=0;
	    $mplwhere["pro.deleted"]=0;
	    $mipro= $MplModel->alias('mpl')
	    ->field('pro.name,pro.id,pro.picUrl,pro.fixedPrice,pro.teambuy,pro.teamPrice,pro.freeBuy,pro.freeBuyMoney,pro.miPrice,pro.playType,
	    	pro.discountedPrice,pro.fromCustomerId,pro.supportSpecification,pro.squarePicUrl,
	    	pro.inventory,pro.inventoryCount,pro.recommend,pro.picUrl1,MIN(spe.discountedPrice) as minDisPrice,
	    	MAX(spe.discountedPrice) as maxDisPrice,MIN(spe.miPrice) as minMiPrice,MAX(spe.miPrice) as maxMiPrice,
	    	MAX(spe.fixedPrice) as maxFixedPrice,MIN(spe.fixedPrice) as minFixedPrice')
	    ->where($mplwhere)
	    ->join("left join wx_module_product pro on pro.id=mpl.pId")
		->join("wx_module_product_specification spe on pro.id=spe.pid")
		->group("pro.id")
	    ->select();
	    foreach ($mipro as $key=>$val){
			if($val["freeBuy"]&&$val["freeBuyMoney"]){
				$mipro[$key]["freeBuyMoney"] = explode(",",$val["freeBuyMoney"]);
			}
			if($val['picUrl1']){
				$val['picUrl1']=json_decode($val['picUrl1'],true);
			}
			$sharewhere['share.moduleId'] = $val['id'];
			$sharewhere['share.module'] = 'product';
			$mater = $shareModel->alias('share')
				->join("left join wx_mishare_material mater on mater.sId=share.id")
				->where($sharewhere)
				->getField("mater.title");
			$val['matitle'] = $mater;
//			 获取规格
	        $pid=$val['id'];
	        if ($val["supportSpecification"] == 1) {
	            $arrFirstSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	            ->order("sepc.id")
	            ->getField("specificationName", true);
	        	$arrFirstSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	            ->order("sepc.id")
	            ->getField("specificationUrl", true);

	            if ($arrFirstSpec) {
	                $val["sizeUnit"] = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");

	            }
	            if($arrFirstSpec){
					$val["size"] = json_encode($arrFirstSpec);
	            }
	            if ($arrFirstSpecurl) {
					$val["sizeurl"] = json_encode($arrFirstSpecurl);
				}
	            $arrSecSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	            ->getField("specificationName", true);
	        	$arrSecSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	            ->getField("specificationUrl", true);

	            if ($arrSecSpec) {
	                $val["colorUnit"] = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");
	            }
	            if($arrSecSpec) {
	            	$val["color"] = json_encode($arrSecSpec);
	            }
	            if ($arrSecSpecurl) {
	            	$val["colorurl"] = json_encode($arrSecSpecurl);
	            }
	            if ($val["inventory"] == 1) {
	            	if (isset($arr['availSku'])) {
	                    $availSku=$arr['availSku'];
	                }else{
	                    $params["pid"] = $val['id'];
	                    $params["arrFirstSpec"] = $arrFirstSpec;
	                    $params["arrSecSpec"] = $arrSecSpec;
	                    $availSku = Module::callModule('product', NULL, 'getProductInventory', $params);
	                }
	                $val["availSku"] = json_encode($availSku);
	            }
				if (!isset($val["availSku"])) {
					$val["availSku"] = json_encode(null);
				}
	        }
	        $mipro[$key]=$val;
	        $newmipro[$pid]=$val;
	    }

		if(!$micon['pointSchemeId']){
			$micon['pointSchemeId'] = $pointScheme_tab->where(['cid' => $customerId, 'default' => 1, 'status' => 1, 'deleted' => 0])->getField('id');
		}
		/*处理积分奖励*/
		if($micon['pointSchemeId']  && $fromUserName){
			R('Point/addVisitPoint', [$micon['pointSchemeId'],$fromUserName,$uid,'micontent',$id,$micon['title'],$customerId]);
		}
	    //添加访问记录
//		$Guid = new Guid();
//		$guid = $Guid->toString();
		Session::switchCustomer($customerId);
		$visitParam=new StdClass();
//		$visitParam->guid=$guid;
//		$visitParam->fromGuid=$param->fromGuid;
        //添加访问记录
        if(!$param->miUId){
            $param->miUId = $miUId;
        }
        if(!$param->qId){
            $param->qId = $qId;
        }

		$visitParam->sId=$micon["sId"];
		$visitParam->miUId=$param->miUId;
		$visitParam->qId=$param->qId;
		$visitParam->fromPage="micontent_detail";
		$visitParam->cid=$customerId;
		$visitParam->visitId= $param->visitId;							//上一次浏览id
		$visitParam->lastShareUId= $param->lastShareUId;							//上一次浏览id
		$visitParam->saleSourceUid= $param->saleSourceUid;							//上一次浏览id
		$visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);
		if($micon['rewardId']){	//产生分享奖励结果
			Session::switchCustomer(0);
			$rewardCfg = M('share_reward')->where(['id'=>$micon['rewardId'],'deleted'=>0])->find();
			if($rewardCfg !== null){
				$rewardCfg['shareRewardCfg'] = M('share_reward_set')->where(['rewardId'=>$micon['rewardId'],'deleted'=>0])->select();
				Session::switchCustomer($customerId);
				if(($rewardCfg['startTime'] <= date('Y-m-d H:i:s')) && $rewardCfg['endTime'] >= date('Y-m-d H:i:s')){
					if(!empty($startUid) || !empty($quanInfo['uId'])){
						R('ShareReward/saveRewardRet', [$id,$customerId,$micon['rewardId'],$rewardCfg,$param->miUId,$uid]);
					}
				}else{
					$micon['rewardId'] = 0;
				}
			}else{
				Log::write('分享奖励id不存在cid:'.$customerId.'|rewardId:'.$micon['rewardId']);
				$micon['rewardId'] = 0;
			}
		}


		if(!(Session::$user['userId'])){
			$micon["isQuan"] = 0;
		}else{
			$micon["isQuan"] = 1;
		}
		//是否显示密友价
		if($qId&&$miUId){
			$isEnjoyMiPrice = 1;
		}else{
			$isEnjoyMiPrice = 0;
		}
		//产品列表
	    $micon['proList']=$mipro;
		//产品详情
	    $micon['prodetail']=json_encode($newmipro);
        $micon["miUId"]=$miUId;
		$micon["userId"]=$uid;
        $micon["qId"]=$qId;
		$micon["mId"]=$id;
		$micon["isEnjoyMiPrice"]=$isEnjoyMiPrice;
        $micon["visitId"]=$visitId;
        $micon['lastShareUId']=$uid;
if(!$param->saleSourceUid){
 $saleSource = $mimall_user_tab->where("uId=$uid and cId=$customerId")->getField('saleSource');
            $micon['saleSourceUid'] = $saleSource;
        }else{
            $micon['saleSourceUid'] = $param->saleSourceUid;
        }

		Session::switchCustomer($customerId);
	    if (!$micon) {
	        Output::instance()->resultCode("素材不存在");
	        return;
	    }
		/*自动分组,改成多账号后,此处没有改动,取消及新增微信分组时会存在问题*/
		$groupId = $tagList->alias("a")
			->join("inner join wx_".$customerId."_user_tag_group b on a.tagId=b.tagId")
			->where("a.webPageId=$id and b.type='content'")->order("b.createTime desc")->getField("b.groupId");

		//存在标签自动分组
		if($groupId){
			//将用户的微信分组全部取消掉,只留下自动分组的这个组id
			$groupList = $allUserModel->where("userName='$userName'")->getField("groupId");
			$groupList = explode(",",$groupList);
			$flag = true;
			$openids[] = $userName;
			foreach($groupList as $key=>$value){
				if($value==$groupId){
					$flag = false;
				}else{
					//批量取消用户的微信标签,
					WeixinApi::deletedUsersTag($openids,$value);
				}
			}
			if($flag){
				//为用户新增微信标签
				WeixinApi::setUsersTag($openids,$groupId);
			}
			if(count($groupList)>1||$groupList[0]!=$groupId){
				$allUserModel->where("userName='$userName'")->setField("groupId",$groupId);
			}
		}
		//销售信息
		$param->currentUid = $uid;
		$micon['currentUid'] = $uid;

        //判断是否展示海报
        $posterWhere['cid'] = array('eq', $customerId);
        $posterWhere['deleted'] = array('eq', 0);
        $posterWhere['status'] = array('eq', 1);
        $posterWhere['module'] = array('eq', 'micontent');
        $posterWhere['moduleId'] = array('eq', $id);
        $posterCount = $posterModel->where($posterWhere)->count();
        $posterCount<=0 ? $micon["isShowPoster"] = 0 : $micon["isShowPoster"] = 1;
        $micon["contactInfo"] = Module::callModule("community", Session::$user,"getContactInfo", $param);
	    Output::instance()->module('micontent',"materiaDetail")->object($micon);
	}
	public function isPartner(){
		$customerId = Session::$user['customerId'];
		$uId=Session::$user['userId'];
		Session::switchCustomer(0);
		$quanModel = M("quan_user");
		Session::switchCustomer($customerId);
		$where["a.uid"]=array("eq",$uId);
		$where['a.deleted']=array("eq",0);
		$where["a.status"]=array("eq",1);
		$where['b.cId'] = array("eq",$customerId);
		$quanInfo = $quanModel->alias("a")
			->join("inner join wx_miyouquan b on a.qid =b.id")
			->where($where)
			->field("a.qid as qId,a.uid as uId,b.miAward")
			->find();
		return $quanInfo;
	}
	/**
	 * [getObjectDetail 获取内容详情页面]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function getObjectDetail($param){
		$customerId = Session::$user["customerId"];
		$uid = Session::$user["userId"];
		Session::switchCustomer(0);
		$ProductModel = M("micontent");
		Session::switchCustomer($customerId);
		$id=$param->id;
		$fromGuid=$param->fromGuid;
		if(!$fromGuid){
			$fromGuid="";
		}
		$result=$ProductModel->field("id,fromCustomerId")->where("id=" . $id)->find();
		if($param->fromUId){
			$fromUId=$param->fromUId;
		}
		if($param->miUId){
			$fromUId=$param->miUId;
		}
		
		$p=new stdClass();
		$p->miUId=$fromUId;
		$p->fromGuid=$fromGuid;
		$p->qId=$param->qId;
		$p->fromUId=$fromUId;
		$p->id=$id;
		$p->sId=$id;
		$formCustomerId=$result["fromCustomerId"];
		$p=urlencode(json_encode($p));
		if($result) {
			$detailUrl=C('SERVER_HOST') . "call.html?customerId=".C("PLANT_CUSTOMERID")."&module=micontent&method=getMiContentDetail&params=$p";
			$result["detailUrl"]=$detailUrl;
			return $result;
		}
	}
	public function getCommentList($param) {
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $start=$param->start;
		$limit=$param->limit;
		$pageStart=$start*$limit;
	    $uid = Session::$user['userId'];
	    $qId=$param->qId;
	    $miUId=$uid;
	    $fromUId=$param->fromUId;
		if($fromUId){
			$miUId=$fromUId;
		}
	    $sId=$param->sId;
		$customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);

	    $shareModel = M("mishare_comment");
	    $where["a.deleted"]=array('eq',0);
	    $where["a.status"]=array('eq',1);
	    $where["a.sId"]=array('eq',$sId);
	    $where["a.qId"]=array('eq',$qId);
	    $order="a.updateTime desc";

	    $list=$shareModel->alias("a")
	    ->join("inner join wx_".$customerId."._user b on a.uId=b.id")
	    ->join("wx_".$customerId."_user_weixin_info c on c.userId=b.id")
			->field("a.*,c.headimgurl,c.nickname")
	    ->where($where)
		->order($order)
		->limit($pageStart, $limit)
		->select();
		foreach ($list as $key => $value) {
			$list[$key]["time"]=format_date(strtotime($value["updateTime"]));
		}
		
		$count =$shareModel->alias("a")
		->join("inner join wx_".$customerId."._user b on a.uId=b.id")
	    ->join("wx_".$customerId."_user_weixin_info c on c.userId=b.id")
		->where($where)
		->order($order)
		->count();
	    
		$comment=new StdClass();
		$comment->count=$count;
		$comment->pageCount=getPageCount($count,$limit);
		$comment->list=$list;
		Output::instance()->object($comment);
	}
	/**
	 * [saveComment 通用分享评论保存]
	 * @param  [type] $param [description]
	 * @return [type]        [description]
	 */
	public function saveComment($param) {
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }

	    $uid = Session::$user['userId'];
	    $id=$param->id;
	    $fromUId=$param->fromUId;
	    $miUId=$uid;
		if($fromUId){
			$miUId=$fromUId;
		}
		$customerId = Session::$user['customerId'];
	    Session::switchCustomer(0);
	    $shareModel = M("mishare_comment");
	    $time=date("Y-m-d H:i:s");
	    $comment=$param->comment;
	    $qId=$param->qId;
	    $addData=array(
	    	"sId"=>$param->sId,
	    	"comment"=>$comment,
	    	"commentImgs"=>$param->commentImgs,
	    	"createTime"=>date("Y-m-d H:i:s"),
	    	"uId"=>$uid,
	    	"miUid"=>$miUId,
	    	"qId"=>$qId,
	    	"status"=>1,
	    	"deleted"=>0,
	    	"updateTime"=>$time
	    );
	    $id=$shareModel->add($addData);
	    
	    if ($id!==false) {
	    	 $result=$shareModel->alias("a")
		    ->join("inner join wx_".$customerId."_user b on a.uId=b.id")
		    ->join("wx_".$customerId."_user_weixin_info c on c.userId=b.id")
				->field("a.*,c.headimgurl,c.nickname")
		    ->where("a.id=".$id)
			->find();
			$result["time"]=format_date(strtotime($time));
			Output::instance()->object($result);
	    } else {
	    	Output::instance()->resultCode(code_sql_error);
	    }
	}

	/**
	 * 获取用户分享的某篇内容数据
	 * 分享人数/浏览人数/线索人数(提交的表单订单)
	 * @param $moduleId  /模块id
	 * @param $type /share/visit/order
	 * @param $start /分页起始
	 * @param $limit /分页偏移
	 * @param $moduleType /模块名
	 * @return object
	 */
	public function getUserMiContentData($moduleId,$type,$start=0, $limit=10, $moduleType='micontent'){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		//只有从社群中分享出来才会记录分享数据
		$cid = Session::$user['customerId'];
		$userId = Session::$user['userId'];
		Session::switchCustomer(0);
		$order_tab = M('module_product_order');
		$shareVisit_tab = M('mishare_visit');
		$shareForm_tab = M('mishare_from');
		Session::switchCustomer($cid);
		$resultList = [];
		$total = 0;
		$shareTotal = $shareForm_tab->alias('a')
			->where(['a.moduleId'=>$moduleId,'a.module'=>$moduleType, 'a.cid'=>$cid, 'a.miUid'=>$userId])
			->field('a.id')
			->group('a.uId')
			->select();
		//Log::write('shareTotal:'.$shareForm_tab->getLastSql());
		$shareTotal = count($shareTotal);
		$visitTotal = $shareVisit_tab->alias('a')
			->where(['a.moduleId'=>$moduleId,'a.module'=>$moduleType, 'a.cid'=>$cid, 'a.miUid'=>$userId])
			->field('a.id')
			->group('a.uId')
			->select();
		$visitTotal = count($visitTotal);
		$orderTotal = $order_tab->alias('a')
			->where(['a.moduleId'=>$moduleId, 'a.fromCustomerId'=>$cid, 'a.miUid'=>$userId,'a.deleted'=>0])
			->field('a.id')
			->select();
		$orderTotal = count($orderTotal);
		switch($type){
			case 'share':
				//分享数
				$resultList = $shareForm_tab->alias('a')
					->join('wx_'.$cid.'_user_weixin_info b on a.uId=b.userId')
					->where(['a.moduleId'=>$moduleId, 'a.cid'=>$cid , 'a.miUid'=>$userId, 'a.module'=>$moduleType])
					->field('a.id as shareId,max(a.createTime) as createTime,sum(a.viewUv) as uv,b.userId, b.nickname, b.headimgurl, b.sex,b.openid')
					->limit($start, $limit)
					->order('a.createTime desc')
					->group('a.uId')
					->select();
				$arr = [];
				foreach($resultList as $k=>$v){
					if($v['uv'] == null){
						$v['uv'] = 0;
					}
					$arr[$k] = $v;
				}
				$resultList = $arr;
				$total = $shareTotal;
				break;
			case 'visit':
				//浏览数
				$resultList = $shareVisit_tab->alias('a')
					->join('wx_'.$cid.'_user_weixin_info b on a.uId=b.userId')
					->where(['a.moduleId'=>$moduleId, 'a.cid'=>$cid , 'a.miUid'=>$userId, 'a.module'=>$moduleType])
					->field('a.id as visitId, max(a.createTime) as createTime,b.userId, b.nickname, b.headimgurl, b.sex')
					->limit($start, $limit)
					->order('createTime desc')
					->group('a.uId')
					->select();
				$total = $visitTotal;
				break;
			case 'order':
				$resultList = $order_tab->alias('a')
					->join('wx_'.$cid.'_user_weixin_info b on a.uId=b.userId')
					->where(['a.moduleId'=>$moduleId, 'a.fromCustomerId'=>$cid , 'a.module'=>$moduleType,
						'a.type'=>'form', 'a.miUid'=>$userId, 'a.deleted'=>0])
					->field('a.id as orderId, a.createTime,b.userId, b.nickname, b.headimgurl, b.sex')
					->limit($start, $limit)
					->order('createTime desc')
					->select();
				$total = $orderTotal;
				break;
			default:
				break;
		}
		if($moduleType == 'micontent'){
			Output::instance()->module($moduleType,"shareInfo")->object([
				'code'=>0,
				'msg'=>'ok',
				'shareTotal'=>$shareTotal,
				'visitTotal'=>$visitTotal,
				'orderTotal'=>$orderTotal,
				'total'=>$total,
				'results'=>$resultList
			]);
		}else{
			Output::instance()->object([
				'code'=>0,
				'msg'=>'ok',
				'shareTotal'=>$shareTotal,
				'visitTotal'=>$visitTotal,
				'orderTotal'=>$orderTotal,
				'total'=>$total,
				'results'=>$resultList
			]);
		}

	}

	/**
	 * 表单订单提交成功后的页面
	 */
	public function formOrderSubmitPage(){
		Output::instance()->module('micontent', 'submitSucc')->object([]);  
	}

	/**
	 * 获取分享奖励信息
	 * @param $param /micontentId
	 */
	public function getRewardInfo($param)
	{
		$cid = Session::$user['customerId'];
		$uid = Session::$user['userId'];
		$micontentId = $param->micontentId;
		$rewardId = $param->rewardId;
		Session::switchCustomer(0);
		$shareReward_tab = M('share_reward');
		$shareRewardSet_tab = M('share_reward_set');
		$shareRewardRet_tab = M('share_reward_result');
		$quanUser_tab = M('quan_user');
		Session::switchCustomer($cid);
		$rewardCfg = $shareReward_tab->where(['id'=>$rewardId,'deleted'=>0,'cid'=>$cid])->find();
		if($rewardCfg == null){
			Log::write('获取分享奖励配置失败cid:'.$cid.'|uid:'.$uid.'|micontent:'.$micontentId.'|sql:'.$shareReward_tab->getLastSql());
		}
		$rewardMap = [];
		$rewardMap['uid'] = $uid;
		$rewardMap['cid'] = $cid;
		$rewardMap['rewardId'] = $rewardId;
		$rewardMap['module'] = 'micontent';
		$rewardMap['deleted'] = 0;
		if(!$rewardCfg['articleNum'] && $rewardCfg['isShare']){
			$rewardMap['moduleId'] = $micontentId;
		}
		$rewardInfo = $shareRewardRet_tab->where($rewardMap)
			->field('id,rewardGrade,status,shareVisitNum,rewardJson,fullName,phone,rewardCause,rewardWay')
			->select();
		if($rewardInfo == null){
			Log::write('获取分享奖励配置失败cid:'.$cid.'|uid:'.$uid.'|micontent:'.$micontentId.'|sql:'.$shareRewardRet_tab->getLastSql());
		}
		$rewardCfg['isShareJson'] = $rewardCfg['isClueJson'] = [];
		//基于分享,存在多等级,多奖励
		if($rewardCfg['isShare']){
			$isShareCfg = $shareRewardSet_tab->where(['rewardId'=>$rewardId,'deleted'=>0])->select();
			$shareCfg = [];
			foreach($isShareCfg as $k=>$v){
				if($v['rewardImgs']){
					$v['rewardImgs'] = explode(',', $v['rewardImgs']);
				}else{
					$v['rewardImgs'] = [];
				}
				$v['shareRewardRet'] = [];
				$shareCfg[$v['rewardGrade']] = $v;
			}
			$rewardCfg['isShareJson'] = $shareCfg;
		}
		//基于线索
		if($rewardCfg['isClue']){
			$rewardCfg['isClueJson']['clueShareRemainder'] = $rewardCfg['clueShareRemainder'];
			$rewardCfg['isClueJson']['clueRewardType'] = $rewardCfg['clueRewardType'];
			$rewardCfg['isClueJson']['clueBlessings'] = $rewardCfg['clueBlessings'];
			$rewardCfg['isClueJson']['clueRedMoney'] = $rewardCfg['clueRedMoney'];
			$rewardCfg['isClueJson']['clueGiftName'] = $rewardCfg['clueGiftName'];
			$rewardCfg['isClueJson']['clueRewardImgs'] = $rewardCfg['clueRewardImgs']?explode(',',$rewardCfg['clueRewardImgs']):[];
			$rewardCfg['isClueJson']['clueRewardRet'] = [];
		}

		if($rewardInfo !== null){
			//奖励信息
			foreach($rewardInfo as $key=>$val){
				$cfgInfo = json_decode($val['rewardJson'], true);
				$val['needSubmit'] = 0;
				if($val['rewardWay'] != 1 && (empty($val['fullName']) || empty($val['phone']))){
					$val['needSubmit'] = 1;	//需要提交领奖信息
				}
				if(intval($val['rewardCause']) == 1){//分享达标,展示领奖时刻的配置信息
					$rewardCfg['isShareJson'][$val['rewardGrade']]['shareRewardRet'] = $val;
					$rewardCfg['isShareJson'][$val['rewardGrade']]['needSubmit'] = $val['needSubmit'];
					unset($val['needSubmit']);
					$rewardCfg['isShareJson'][$val['rewardGrade']]['rewardId'] = $cfgInfo['rewardId'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['visitCount'] = $cfgInfo['visitCount'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['rewardGrade'] = $cfgInfo['rewardGrade'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['shareRemainder'] = $cfgInfo['shareRemainder'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['rewardType'] = $cfgInfo['rewardType'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['blessings'] = $cfgInfo['blessings'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['clueGiftName'] = $cfgInfo['clueGiftName'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['redMoney'] = $cfgInfo['redMoney'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['rewardImgs'] = $cfgInfo['rewardImgs']?explode(',',$cfgInfo['rewardImgs']):[];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['createTime'] = $cfgInfo['createTime'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['articleNum'] = $cfgInfo['articleNum'];
					$rewardCfg['isShareJson'][$val['rewardGrade']]['endTime'] = $cfgInfo['endTime'];
					if($cfgInfo['rewardType'] == 1){
						$rewardCfg['isShareJson'][$val['rewardGrade']]['clueGiftName'] = '';
						$rewardCfg['isShareJson'][$val['rewardGrade']]['rewardImgs'] = [];
					}else{
						$rewardCfg['isShareJson'][$val['rewardGrade']]['blessings'] = '';
						$rewardCfg['isShareJson'][$val['rewardGrade']]['redMoney'] = 0;
					}
				}
				if(intval($val['rewardCause']) == 2){//线索达标
					$val['clueShareRemainder'] =  $cfgInfo['clueShareRemainder'];
					$val['clueRewardType'] =  $cfgInfo['clueRewardType'];
					$val['clueBlessings'] =  $cfgInfo['clueBlessings'];
					$val['clueRedMoney'] =  $cfgInfo['clueRedMoney'];
					$val['clueGiftName'] =  $cfgInfo['clueGiftName'];
					$val['clueRewardImgs'] =  $cfgInfo['clueRewardImgs']?explode(',',$cfgInfo['clueRewardImgs']):[];
					$val['endTime'] =  $cfgInfo['endTime'];
					if($cfgInfo['clueRewardType'] == 1){
						$val['clueGiftName'] = '';
						$val['clueRewardImgs'] = [];
					}else{
						$val['clueBlessings'] = '';
						$val['clueRedMoney'] = 0;
					}
					$rewardCfg['isClueJson']['clueRewardRet'][] = $val;
				}
			}
		}

		$rewardCfg['miContentId'] = $micontentId;
		//圈子主题色
		$quanCfg = $quanUser_tab->alias('a')
			->join('inner join wx_miyouquan b on a.qid=b.id')
			->where(['a.uid'=>$uid,'a.deleted'=>0,'a.status'=>1])
			->getfield('config');
		$themeColor = json_decode($quanCfg, true)['reveal']['themeColor'];
		$rewardCfg['themeColor'] = $themeColor;
		Output::instance()->module('micontent', 'reward')->object($rewardCfg);
	}

	/**
	 * 密友圈菜单"我的分享奖励"
	 * @param $params
	 */
	public function getMiUserRewardList($params)
	{
		$start = $params->start;
		$limit = $params->limit;
		$cid = Session::$user['customerId'];
		$uid = Session::$user['userId'];
		Session::switchCustomer(0);
		$rewardRet_tab = M('share_reward_result');
		$rewardSet_tab = M('share_reward_set');
		$reward_tab = M('share_reward');
		$quanUser_tab = M('quan_user');
		Session::switchCustomer($cid);
		$rewardList = $rewardRet_tab->alias('a')
			->join('wx_micontent b on a.moduleId=b.id')
			->field('a.*, b.title')
			->where(['a.uid'=>$uid,'a.cid'=>$cid,'a.deleted'=>0])
			->limit($start,$limit)
			->order('a.createTime desc')
			->select();
		if($rewardList == null){
			Output::instance()->object([
				'code'=>-1,
				'msg'=>'暂无奖励',
				'results'=>[]
			]);
			return;
		}
		//圈子主题色
		$quanCfg = $quanUser_tab->alias('a')
			->join('inner join wx_miyouquan b on a.qid=b.id')
			->where(['a.uid'=>$uid,'a.deleted'=>0,'a.status'=>1])
			->getfield('config');
		$themeColor = json_decode($quanCfg, true)['reveal']['themeColor'];
		foreach($rewardList as $key=>$val){
			$val['themeColor'] = $themeColor;
			$cfgInfo = json_decode($val['rewardJson'], true);
			$val['needSubmit'] = 0;
			if($val['rewardWay'] != 1 && (empty($val['fullName']) || empty($val['phone']))){
				$val['needSubmit'] = 1;	//需要提交领奖信息
			}
			$val['rewardJson'] = $cfgInfo;
			if(intval($val['rewardCause']) == 2){
				$val['newShareRemainder'] = $reward_tab->where(['id'=>$val['rewardId']])->getField('clueShareRemainder');
				$val['clueShareRemainder'] =  $cfgInfo['clueShareRemainder'];
				$val['clueRewardType'] =  $cfgInfo['clueRewardType'];
				$val['clueBlessings'] =  $cfgInfo['clueBlessings'];
				$val['clueGiftName'] =  $cfgInfo['clueGiftName'];
				$val['clueRedMoney'] =  $cfgInfo['clueRedMoney'];
				$val['clueRewardImgs'] =  $cfgInfo['clueRewardImgs']?explode(',',$cfgInfo['clueRewardImgs']):[];
				if($val['clueRewardType'] == 1){
					$val['clueGiftName'] = '';
					$val['clueRewardImgs'] = [];
				}else{
					$val['clueBlessings'] = '';
					$val['clueRedMoney'] = 0;
				}
				$val['endTime'] =  $cfgInfo['endTime'];
			}else{
				//$val['rewardId'] = $cfgInfo['rewardId'];
				$val['newShareRemainder'] = $rewardSet_tab->where(['rewardId'=>$val['rewardId'],'cid'=>$cid])->getField('shareRemainder');
				$val['visitCount'] = $cfgInfo['visitCount'];
				$val['rewardGrade'] = $cfgInfo['rewardGrade'];
				$val['shareRemainder'] = $cfgInfo['shareRemainder'];
				$val['rewardType'] = $cfgInfo['rewardType'];
				$val['blessings'] = $cfgInfo['blessings'];
				$val['clueGiftName'] = $cfgInfo['clueGiftName'];
				$val['redMoney'] = $cfgInfo['redMoney'];
				$val['rewardImgs'] = $cfgInfo['rewardImgs']?explode(',', $cfgInfo['rewardImgs']):[];
				//$val['createTime'] = $cfgInfo['createTime'];
				$val['articleNum'] = $cfgInfo['articleNum'];
				$val['endTime'] = $cfgInfo['endTime'];
				if($cfgInfo['rewardType'] == 1){
					$val['clueGiftName'] = '';
					$val['rewardImgs'] = [];
				}else{
					$val['blessings'] = '';
					$val['redMoney'] = 0;
				}
			}
			$rewardList[$key] = $val;
		}
		$total = $rewardRet_tab->alias('a')
			->join('wx_micontent b on a.moduleId=b.id')
			->field('a.id')
			->where(['a.uid'=>$uid,'a.cid'=>$cid,'a.deleted'=>0])
			->count();
		Output::instance()->object([
			'code'=>0,
			'total'=>$total,
			'msg'=>'ok',
			'results'=>$rewardList
		]);
	}

	/**
	 * 提交填写奖励信息页面
	 */
	public function receiveReward()
	{
		$cid = Session::$user['customerId'];
		$uid = Session::$user['userId'];
		Session::switchCustomer(0);
		$quanUser_tab = M('quan_user');
		Session::switchCustomer($cid);
		$userInfo = $quanUser_tab->alias('a')
			->join('inner join wx_miyouquan b on a.qid=b.id')
			->join('wx_'.$cid.'_user c on a.uid=c.id')
			->where(['a.uid'=>$uid,'a.deleted'=>0,'a.status'=>1])
			->field('b.config,c.county,c.town,c.rural,c.fullName,c.phone,c.email,c.city,c.province,c.birthday,c.address')
			->find();
		$themeColor = json_decode($userInfo['config'], true)['reveal']['themeColor'];
		unset($userInfo['config']);
		$userInfo['themeColor'] = $themeColor;
		Output::instance()->module('micontent', 'receiveReward')->object(['userInfo'=>$userInfo]);
	}

	/**
	 * 保存分享奖励用户提交的信息
	 * @param $param /提交的信息
	 */
	public function RewardSubmitInfo($param)
	{
		$cid = Session::$user['customerId'];
		$uid = Session::$user['userId'];
		Session::switchCustomer(0);
		$shareRewardRet_tab = M('share_reward_result');
		Session::switchCustomer($cid);
		$rewardId = $param->rewardId;
		$moduleId = $param->moduleId;
		if(!$rewardId || !$moduleId){
			Output::instance()->object([
				'code'=>-1,
				'msg'=>'信息缺失'
			]);
			return;
		}
		$data = [];
		$data['fullName'] = $param->fullName;
		$data['phone'] = $param->phone;
		$data['city'] = $param->city;
		$data['province'] = $param->province;
		$data['county'] = $param->county;
		$data['address'] = $param->address;
		$data['noGrantTime'] = date('Y-m-d H:i:s');
		$saveRet = $shareRewardRet_tab->where(['id'=>$rewardId])->save($data);
		//Log::write('奖励提交信息失败cid:'.$cid.'|sql:'.$shareRewardRet_tab->getLastSql());
		if(!is_numeric($saveRet)){
			Log::write('奖励提交信息失败cid:'.$cid.'|sql:'.$shareRewardRet_tab->getLastSql());
			Output::instance()->object([
				'code'=>-1,
				'msg'=>'提交失败',
				'results'=>[]
			]);
			return;
		}
		Output::instance()->object([
			'code'=>0,
			'msg'=>'提交成功',
			'retsult'=>[]
		]);
	}

    /**统计阅读时间，每三秒调用一次
     * @param $visitId
     */
	public function saveVisitTime($visitId)
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $mishareVisitModel = M('mishare_visit');
        Session::switchCustomer($customerId);

        $where = [
            'visitId' => $visitId
        ];

        $visitTime = $mishareVisitModel->where($where)->getField('visitTime');
        if (empty($visitTime)) $visitTime = 0;
        $visitTime += 3;
        $mishareVisitModel->where($where)->setField('visitTime', $visitTime);

        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok'
        ]);
    }
}
